package com.pack;

import java.util.Calendar;
import model.ContactUser;
import client.StubClient;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
	//variabili globali
	private TextView viewData, viewNomeSanto;
	private String currentDate;
	private StubClient stub;
	private ContactUser usr;
	private String nomeSanto;
	private Spinner spinnerMode;
	private Button buttonSubmit;
	private DbAdapter adapter=new DbAdapter(this);
	private Cursor cursor;
	private String contacts="", numbers="";
	private SharedPreferences prefs;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //visualizza il layout
        setContentView(R.layout.main);
        
        //calendario per impostazione data
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        currentDate=cal.getTime().getDate()+"-"+(cal.getTime().getMonth()+1)+"";
        
        //aggiornamento TextView data
        viewData = (TextView) findViewById(R.id.textViewData);
        viewData.setText(currentDate+"-"+(1900+cal.getTime().getYear()));
        
        // Richiesta al server per farsi dire il santo del giorno
        stub = new StubClient();
	    usr = new ContactUser();
	    usr = stub.selectByDate(currentDate);
	    nomeSanto = usr.getNome();
	    viewNomeSanto = (TextView)findViewById(R.id.textViewNomeSanto);
	    viewNomeSanto.setText("S. "+nomeSanto+"");
	    
	    //Metodo per intervenire sulla selezione di un item dello spinner
	    spinnerMode = (Spinner) findViewById(R.id.spinner_mode);
		spinnerMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			 public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
				Toast.makeText(parent.getContext(),"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),Toast.LENGTH_SHORT).show();
			 }
			 public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			 }
		});
		
		//query al database
		
		adapter.open();
		cursor=adapter.getContactsInfo(nomeSanto);
		//cursor=adapter.getContactsInfo("Tre,Wind"); //**********************************************************
		while(cursor.moveToNext()){
			contacts=contacts+cursor.getString(0)+",";
			numbers=numbers+cursor.getString(1)+";";
		}
		adapter.close();
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		
		//Metodo per intervenire sul click del pulsante "Invia Auguri"
		buttonSubmit = (Button) findViewById(R.id.buttonAuguri);
		buttonSubmit.setOnClickListener(new OnClickListener() {
			  public void onClick(View v) {
			    Toast.makeText(MainActivity.this,"OnClickListener : " + 
		                "\nSpinner Mode : "+ String.valueOf(spinnerMode.getSelectedItem()),Toast.LENGTH_SHORT).show();
			    
			    if(cursor.getCount()==0){
			    	Toast.makeText(MainActivity.this,"Nessun nome in rubrica!",Toast.LENGTH_SHORT).show();
			    }
			    else{
			    	//copia i dati da passare all'activity successiva in un bundle
	                final Bundle bundle = new Bundle();
	                //bundle.putString("mode", String.valueOf(spinnerMode.getSelectedItem()));
	                bundle.putString("contacts", contacts);
	                
	                String mode = String.valueOf(spinnerMode.getSelectedItem());
	                if(mode.equalsIgnoreCase("sms")){
	                	try {
	                		
	                		String textPref = prefs.getString("text", "");
	               		 	//avvia l'activity di default di android per l'invio degli sms
	                		Intent sendIntent = new Intent(Intent.ACTION_VIEW);
	    				    sendIntent.putExtra("sms_body", textPref);
	    				    sendIntent.putExtra("address", numbers);
	    				    sendIntent.setType("vnd.android-dir/mms-sms");
	    				    startActivity(sendIntent);

	    				} catch (Exception e) {
	    					Toast.makeText(getApplicationContext(),"SMS failed, please try again later!",Toast.LENGTH_LONG).show();
	    					e.printStackTrace();
	    				}
	                }
	                else{
	                	 //crea l'Intent per la chiamata alla prossima activity
	                    Intent selection_intent = new Intent(MainActivity.this, SendMailActivity.class);
	                    selection_intent.putExtras(bundle);
	                    startActivity(selection_intent);
	                }
	                
	               
	                //termina l'activity corrente
	                MainActivity.this.finish();
			    }
			    
			  }
		 
		});
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuItem comandoNew=menu.add(Menu.NONE, MENUITEM_COMANDO_ADDCONTACT, 1, "Add Contact");
    	comandoNew.setIcon(R.drawable.plus);
    	MenuItem comandoSearch=menu.add(Menu.NONE, MENUITEM_COMANDO_SEARCHCONTACT, 2, "Contact Search");
    	comandoSearch.setIcon(R.drawable.search);
    	MenuItem comandoSetting=menu.add(Menu.NONE, MENUITEM_COMANDO_SETTING, 3, "Settings");
    	comandoSetting.setIcon(R.drawable.settings);
    	return true;    	
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	int id=item.getItemId();
    	switch (id) {
    	case MENUITEM_COMANDO_ADDCONTACT:
    		Intent intentAddContact=new Intent(this, AddContactActivity.class);
    		startActivity(intentAddContact);
    		return true;
    	case MENUITEM_COMANDO_SEARCHCONTACT:
    		Intent intentSearchContact=new Intent(this, ListViewActivity.class);
    		startActivity(intentSearchContact);
    		return true;
    	case MENUITEM_COMANDO_SETTING:
    		Intent intentSetting=new Intent(this, SettingActivity.class);
    		startActivity(intentSetting);
    		return true;
    	}
    	return false;
    }
    
    private static final int MENUITEM_COMANDO_ADDCONTACT = 1;
    private static final int MENUITEM_COMANDO_SEARCHCONTACT = 2;
    private static final int MENUITEM_COMANDO_SETTING = 3;
}
